<template>
	<view class="page-chat" :style="pagePaddingTop">
		<custom-nav :showBackArrow="true" :title="'详情'">
			<template #navRight>
				<view class="box-share" :style="[otherStyle]">
					<image class="icon-share" src="/static/icon_share.png" @tap="onShare"></image>
					<!-- #ifdef MP-WEIXIN -->
					<button open-type="share" class='btn-share'></button>
					<!-- #endif -->
				</view>
			</template>
		</custom-nav>
		<view class="container-back">
			<view class="wrap-icon-back" @tap="onHistory">
				<image class="icon-back" src="/static/icon_arrow_left.png"></image>
			</view>
		</view>
		<view class="container-chat-body" id='refContent'>
			<view v-for="(item,idx) in list" :key="idx"
				:class="['container-chat-item',item.messageType==102?'openai':'',item.messageType==101?'self':'']">
				<view class="box-chat-item">
					<view class="container-chat-item-main">
						<view class="cont-chat-message">
							<template v-if="item.messageType==101">{{item.show_mid_table_remark_001}}</template>
							<template v-if="item.messageType==102">{{item.show_mid_table_remark_002}}</template>
						</view>
					</view>
				</view>
				<view :class="['box-chat-operation',item.messageType==101?'my':'',item.messageType==102?'openai':'']">

					<template v-if="item.messageType==102">
						<view
							:class="['box-icon-operation',(item.show_save_data_004&&(item.show_save_data_004.is_online===0||item.show_save_data_004.is_online==='0'))?'activated':'']"
							@tap="onCollect(item)">
							<image :class="['icon-img','collect']"
								:src="(item.show_save_data_004&&(item.show_save_data_004.is_online===0||item.show_save_data_004.is_online==='0'))?'/static/chat/icon_collect_selected.png':'/static/chat/icon_collect.png'">
							</image>
						</view>
						<view
							:class="['box-icon-operation',(item.show_save_data_003&&(item.show_save_data_003.is_online===0||item.show_save_data_003.is_online==='0'))?'activated':'']"
							@tap="onLike(item)">
							<image :class="['icon-img','like']"
								:src="(item.show_save_data_003&&(item.show_save_data_003.is_online===0||item.show_save_data_003.is_online==='0'))?'/static/chat/icon_like_selected.png':'/static/chat/icon_like.png'">
							</image>
						</view>
						<view class="box-icon-operation" @tap="onCopy(item)">
							<image :class="['icon-img','copy']" src="/static/icon_chat_detail_copy.png"></image>
						</view>
					</template>

				</view>
			</view>
		</view>

		<view class="container-bottom" @tap="handleToChat">
			<view class="btn">继续提问
				<view class="icon-go">
					<image class="img-go" src="/static/icon_more_arrow.png"></image>
				</view>
			</view>
		</view>
	</view>
	<custom-share v-model:visible='showShare' :title="shareTitle" :link="shareUrl"
		:bodyBg="{background:'#182836','paddingBottom':'40rpx'}"></custom-share>
	<custom-modal v-model:visible='showCopyDialog' content='您确定要在该记录上继续提问题吗？' :showCancelButton='true'
		@clickCallback="onContinueQA"></custom-modal>
</template>

<script setup>
	import {
		ref,
		nextTick,
		reactive,
		computed
	} from "vue"
	import {
		onLoad,
		onPageScroll,
		onReachBottom,
		onShareAppMessage
	} from '@dcloudio/uni-app'
	import {
		showToast
	} from "@/utils/frameApi"
	import {
		showDecodeBase64,
		showBRContent,
		encodeBase64
	} from "@/utils/tool.js"
	import {
		getNavHeightTop
	} from "@/stores/navStore.js"
	import {
		useUser
	} from "@/hooks/useUser.js"

	import CustomNav from "@/components/custom-nav/index.vue"
	import CustomShare from "@/components/custom-share/index.vue"
	import CustomModal from "@/components/custom-modal/index.vue"
	import {
		middleAPI
	} from "@/http/apis/middleAPI.js"
	import {
		chatGPTAPI
	} from "@/http/apis/chatAPI.js"

	let navHeightInfo = getNavHeightTop();
	const pagePaddingTop = ref({
		"paddingTop": navHeightInfo.navTotalHeight + 'px'
	})
	let otherStyle = ref({})
	// #ifdef MP-WEIXIN
	let rpx10 = uni.upx2px(10);
	let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
	let right = menuButtonInfo.width + rpx10;
	otherStyle.value = {
		marginRight: `${right}px`
	}
	// #endif
	const userStore = useUser();
	// 用户信息
	let userInfo = ref(null)
	userStore.getUserInfo().then(async res => {
		userInfo.value = res?.public_user_info || {};
	}, err => {
		console.log(err, '>>>userinfo')
	})
	let industryId = ref("")
	let tag = ref("")
	let chatSessionId = ref("")
	const scrollToBottom = () => {
		return new Promise((resolve, reject) => {
			nextTick(() => {
				let query = uni.createSelectorQuery()
				query.select(`#refContent`).boundingClientRect((res) => {
					uni.pageScrollTo({
						scrollTop: res.height,
						duration: 0
					})
					resolve(res);
				}).exec();
			})
		})
	}

	let list = ref([])
	let page = ref(1);
	let notMore = ref(false)
	const getList = async () => {
		const pageSize = 50
		let queryParas = {
			invoke_method: 'public_load_middle_table_list',
			pre_db_para_middle_table_name: 'public_middle_table_lite_mod_ai_chatgpt',
			type_middle_app: 30001,
			type_inner_app: 1001,
			is_online: 0,
			pre_db_para_begin_idx: (page.value - 1) * pageSize,
			pre_db_para_length_4_list: pageSize,
			pre_db_para_order_by_para: 'id_public_middle_table ASC',
			pre_cmd_para_show_main_info: true,
			mid_table_remark_008: industryId.value,
			mid_table_remark_015_like: tag.value,
			mid_table_remark_013_in: chatSessionId.value
		}
		let response = await middleAPI(queryParas).catch((err) => {
			console.log(err, ">>>getSessionIdChatList")
			let nextPage = page.value - 1;
			page.value = nextPage > 0 ? nextPage : 1;
		})
		if (response) {
			let result = response?.page_content || []
			let showResultList = []
			try {
				result.forEach(item => {
					item.show_mid_table_remark_001 = item.mid_table_remark_001;
					item.show_mid_table_remark_002 = item.mid_table_remark_002;
					item.show_mid_table_remark_001 = showBRContent(showDecodeBase64(item
						.show_mid_table_remark_001))
					item.show_mid_table_remark_002 = showBRContent(showDecodeBase64(item
						.show_mid_table_remark_002))
					item.show_save_data_003 = ((item?.save_data_003 || [])[0]) || null
					item.show_save_data_004 = ((item?.save_data_004 || [])[0]) || null
					showResultList.push(Object.assign({
						messageType: 101
					}, item))
					showResultList.push(Object.assign({
						messageType: 102
					}, item))
				})
			} catch (e) {
				//TODO handle the exception
				console.log(e)
			}
			let tmpList = list.value;
			tmpList = showResultList.concat(tmpList)
			list.value = tmpList
		}
		// scrollToBottom();
	}

	const onHistory = () => {
		uni.navigateBack()
	}
	// 收藏
	const onCollect = async (item) => {
		if (item && item.id_public_middle_table) {
			if (item.show_save_data_004) {
				let queryParas = {
					invoke_method: "public_insert_or_update_middle_table",
					pre_db_para_middle_table_name: "public_middle_table_lite_mod_favorite_things",
					pre_db_para_id_public_middle_table: item.show_save_data_004.id_public_middle_table,
					is_online: (item.show_save_data_004.is_online && item.show_save_data_004.is_online !==
						'0') ? 0 : 1,
				}
				middleAPI(queryParas).then(() => {
					item.show_save_data_004.is_online = (item.show_save_data_004.is_online && item
						.show_save_data_004.is_online !== '0') ? 0 : 1
				}, err => {
					console.log(err, ">>>>>")
				})
			} else {
				let queryParas = {
					invoke_method: "public_insert_or_update_middle_table",
					pre_db_para_middle_table_name: "public_middle_table_lite_mod_favorite_things",
					is_online: 0,
					id_public_user_info: userInfo?.value?.id_public_user_info || '',
					mid_table_remark_001: item.mid_table_remark_001,
					mid_table_remark_002: item.mid_table_remark_002,
					mid_table_remark_013: item.mid_table_remark_013,
					mid_table_remark_017: userInfo?.value?.nick_name || '-1',
					mid_table_remark_018: userInfo?.value?.user_phone || '-1',
					mid_table_remark_019: userInfo?.value?.weichat_img || '-1',
					table_id_father: item.id_public_middle_table,
					type_middle_app: 90001,
					type_inner_app: 1001,
				}
				let response = await middleAPI(queryParas).catch((err) => {
					console.log(err)
				})
				if (response) {
					item.show_save_data_004 = response?.page_content[0] || null
				}
			}
		}
	}
	// 点赞
	const onLike = async (item) => {
		if (item && item.id_public_middle_table) {
			if (item.show_save_data_003) {
				let queryParas = {
					invoke_method: "public_insert_or_update_middle_table",
					pre_db_para_middle_table_name: "public_middle_table_lite_mod_favorite_things",
					pre_db_para_id_public_middle_table: item.show_save_data_003.id_public_middle_table,
					is_online: (item.show_save_data_003.is_online && item.show_save_data_003.is_online !==
						'0') ? 0 : 1,
				}
				middleAPI(queryParas).then(() => {
					item.show_save_data_003.is_online = (item.show_save_data_003.is_online && item
						.show_save_data_003.is_online !== '0') ? 0 : 1
				}, err => {
					console.log(err, ">>>>>")
				})
			} else {
				let queryParas = {
					invoke_method: "public_insert_or_update_middle_table",
					pre_db_para_middle_table_name: "public_middle_table_lite_mod_favorite_things",
					is_online: 0,
					id_public_user_info: userInfo?.value?.id_public_user_info || '',
					mid_table_remark_001: item.mid_table_remark_001,
					mid_table_remark_002: item.mid_table_remark_002,
					mid_table_remark_013: item.mid_table_remark_013,
					mid_table_remark_017: userInfo?.value?.nick_name || '-1',
					mid_table_remark_018: userInfo?.value?.user_phone || '-1',
					mid_table_remark_019: userInfo?.value?.weichat_img || '-1',
					table_id_father: item.id_public_middle_table,
					type_middle_app: 90001,
					type_inner_app: 2002,
				}
				let response = await middleAPI(queryParas).catch((err) => {
					console.log(err)
				})
				if (response) {
					item.show_save_data_003 = response?.page_content[0] || null
				}

			}
		}
	}
	// 复制
	const onCopy = (item) => {
		if (item && item.show_mid_table_remark_002) {
			uni.setClipboardData({
				data: item.show_mid_table_remark_002,
				showToast: false,
				success: function() {
					showToast({
						title: "内容已复制"
					})
				}
			});
		}
	}


	// 去聊天，并带上当前会话ID拉取会话数据
	const showCopyDialog = ref(false);
	let requesting = false;
	// 判断已经复制过
	const onQueryOrContinueSession = async () => {
		let queryData = {
			invoke_method: 'public_load_middle_table_list',
			pre_db_para_middle_table_name: 'public_middle_table_lite_mod_ai_chatgpt',
			type_middle_app: 10001,
			type_inner_app: 1001,
			is_online: 0,
			pre_db_para_begin_idx: 0,
			pre_db_para_length_4_list: 10,
			pre_db_para_order_by_para: 'id_public_middle_table DESC',
			pre_cmd_para_show_main_info: true,
			id_public_user_info: userInfo.value.id_public_user_info,
			mid_table_remark_023: chatSessionId.value,
			// pre_db_para_group_by_para: "mid_table_remark_013",
		}
		let response = await middleAPI(queryData, false).catch(err => {
			console.log(err)
			return Promise.reject(err)
		});
		if (response) {
			console.log(response, ">>>history...")
			if (response.page_content && response.page_content.length > 0) {
				return Promise.resolve(response.page_content)
			} else {
				return Promise.resolve([])
			}
		}

	}

	const onCopySession = async () => {
		const copyParams = {
			invoke_method: 'save_data_to_user_id',
			pre_cmd_para_session_id: chatSessionId.value,
			pre_cmd_para_dest_id_user: userInfo.value.id_public_user_info
		}
		let copyResponse = await chatGPTAPI(copyParams, false).catch(err => {
			console.log(err, ">>>copysession")
			return Promise.reject(err)
		})
		if (copyResponse) {
			return Promise.resolve(copyResponse)
		}
	}
	const handleToChat = async () => {
		if (requesting) {
			return;
		}
		requesting = true;
		let oldResult = await onQueryOrContinueSession().catch((err) => {
			console.log(err, ">>>");
			requesting = false;
		})
		if (oldResult) {
			requesting = false;
			if (oldResult.length > 0) {
				uni.navigateTo({
					url: `/pages/chat/index?id=${industryId.value}&sessionid=${ oldResult[0].mid_table_remark_013}`
				})
			} else {
				showCopyDialog.value = true;
			}
		}

		return;

	}
	const onContinueQA = async (confirm) => {
		if (confirm) {
			let copyResponse = await onCopySession().catch((err) => {
				console.log(err, ">>>")
			})
			if (copyResponse) {
				if (copyResponse.new_sessionId) {
					uni.navigateTo({
						url: `/pages/chat/index?id=${industryId.value}&sessionid=${ copyResponse.new_sessionId}`
					})
				}
			}
		}
	}
	let shareUrl = reactive("")
	onLoad((options) => {
		industryId.value = options.id || "";
		tag.value = options.subname ? decodeURIComponent(options.subname) : '';
		chatSessionId.value = options.sessionId ? decodeURIComponent(options.sessionId) : ""
		if (!industryId.value || !chatSessionId.value) {
			uni.navigateBack()
			return
		}
		shareUrl =
			`https://duzikai4aigcugc5001.downline.cn/004_mobile_web_site_lite_mod__aigc_ugc/dist/index.html#/shareclassic?industryid=${industryId.value}&sessionId=${chatSessionId.value}`
		getList()
	})


	// 加载更多
	onReachBottom(() => {
		if (notMore.value) {
			return;
		}
		page.value += 1;
		getList()
	})
	// 分享
	let showShare = ref(false)
	const shareTitle = computed(() => {
		if (list.value && list.value[0]) {
			return `旅游助手-${list.value[0].show_mid_table_remark_001}`
		}
		return "旅游助手"
	})
	const onShare = () => {
		showShare.value = true;
		return;
		let url =
			`https://duzikai4aigcugc5001.downline.cn/004_mobile_web_site_lite_mod__aigc_ugc/dist/index.html#/shareclassic?industryid=${industryId.value}&sessionId=${chatSessionId.value}`
		console.log(url, ">>>url")
		// #ifdef APP-PLUS
		uni.share({
			provider: "weixin",
			scene: "WXSceneTimeline",
			type: 0,
			href: url,
			title: "旅游助手",
			summary: "您的AI私人助手",
			imageUrl: "https://duzikai4aigcugc5001.downline.cn/004_mobile_web_site_lite_mod__aigc_ugc/dist/img/logo@3x.1ec3bfe2.png",
			success: (res) => {
				console.log(res)
			},
			fail: (err) => {
				console.log(err, "err")
			}
		})
		/*
		plus.share.sendWithSystem({
			// type: 'text',
			// content: '分享内容',
			// href: 'http://www.dcloud.io/',
			// img:"/static/logo.png",
			
			href:url,
			title:"旅游助手",
			summary:"您的AI私人助手",
			imageUrl:"https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png",
			
		}, function() {
			console.log('分享成功');
		}, function(e) {
			console.log('分享失败：' + JSON.stringify(e));
		});
		*/
		// uni.share({
		// 	provider: "weixin",
		// 	scene: "WXSceneSession",
		// 	type: 0,
		// 	href: "https://www.duzikai.com",
		// 	title: "AI出门旅行助手",
		// 	summary: "AI出门旅行助手",
		// 	imageUrl: "/static/logo.png",
		// 	success: function (res) {
		// 		console.log("success:" + JSON.stringify(res));
		// 	},
		// 	fail: function (err) {
		// 		console.log("fail:" + JSON.stringify(err));
		// 	}
		// });
		// #endif
	}
	onShareAppMessage((info) => {
		console.log(info, ">>")
	})
</script>

<style lang="less" scoped>
	.page-chat {
		position: relative;
		width: 100%;
		min-height: 100vh;
		padding-top: 80rpx;
		padding-bottom: 203rpx;
		box-sizing: border-box;
		background-color: #182836;
		display: flex;
		display: -wekbit-flex;
		flex-direction: column;

		.container-back {
			position: fixed;
			top: 0;
			width: 100%;
			height: 80rpx;
			padding-top: 2rpx;
			padding-left: 32rpx;
			padding-right: 32rpx;
			background-color: #182836;
			box-sizing: border-box;
			z-index: 3;

			.wrap-icon-back {
				position: relative;
				width: 76rpx;
				height: 76rpx;
				background: #121F2B;
				border-radius: 50%;

				.icon-back {
					position: absolute;
					width: 21rpx;
					height: 37rpx;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
					-webkit-transform: translate(-50%, -50%);
				}
			}
		}

		.container-chat-body {
			position: relative;
			width: 100%;
			padding-left: 32rpx;
			padding-right: 32rpx;
			padding-top: 18rpx;
			box-sizing: border-box;

			.container-chat-item {
				position: relative;
				width: 100%;
				margin-bottom: 40rpx;

				.box-chat-item {
					position: relative;
					width: 100%;
					display: flex;
					display: -webkit-flex;
					flex-direction: row;

					.container-chat-item-main {
						position: relative;
						flex: auto;
						width: 0;
						display: flex;
						display: -webkit-flex;
						flex-direction: row;

						.cont-chat-message {
							position: relative;
							max-width: 100%;
							padding: 30rpx;
							box-sizing: border-box;
							font-size: 30rpx;
							// font-family: PingFang SC;
							font-weight: 400;
							color: #FFFFFF;
							line-height: 48rpx;
							text-align: justify;
							white-space: pre-wrap;
						}
					}
				}

				.box-chat-operation {
					position: relative;
					width: 100%;
					display: flex;
					display: -webkit-flex;
					flex-direction: row;
					align-items: center;

					&.my {
						margin-top: 24rpx;
					}

					&.openai {
						margin-top: 20rpx;
					}

					.box-edit {
						position: relative;
						display: flex;
						display: -webkit-flex;
						flex-direction: row;
						align-items: center;

						font-size: 28rpx;
						// font-family: PingFang SC;
						font-weight: 400;
						color: #FFFFFF;
						line-height: 28rpx;

						.icon-edit {
							position: relative;
							width: 26rpx;
							height: 26rpx;
							margin-right: 10rpx;
						}
					}

					.box-icon-operation {
						position: relative;
						width: 50rpx;
						height: 50rpx;
						background: #2D4052;
						border-radius: 50%;
						box-sizing: border-box;
						margin-right: 28rpx;

						&.activated {

							background: rgba(0, 255, 246, 1);
						}

						&:last-child {
							margin-right: 0;
						}

						.icon-img {
							position: absolute;
							top: 50%;
							left: 50%;
							transform: translate(-50%, -50%);
							-webkit-transform: translate(-50%, -50%);
							width: 30rpx;
							height: 30rpx;




						}
					}
				}

				&.self {
					.box-chat-item .container-chat-item-main {
						justify-content: flex-end;
					}

					.box-chat-item .container-chat-item-main .cont-chat-message {
						color: #182836;
						background: #00FFF6;
						border-radius: 44rpx 4rpx 44rpx 44rpx;
					}

					.box-chat-operation {
						justify-content: flex-end;
					}
				}

				&.openai {
					.box-chat-item .container-chat-item-main .cont-chat-message {
						background: #2D4052;
						border-radius: 4rpx 32rpx 32rpx 32rpx;
					}

				}



			}

			.box-wait {
				position: relative;
				width: 154rpx;
				height: 88rpx;
				background: #2D4052;
				border-radius: 12rpx 44rpx 44rpx 44rpx;
				text-align: center;
				line-height: 88rpx;
				box-sizing: border-box;
				display: flex;
				display: -webkit-flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				.dot {
					position: relative;
					width: 14rpx;
					height: 14rpx;
					background: #FFFFFF;
					border-radius: 50%;
					margin-right: 16rpx;

					&:last-child {
						margin-right: 0;
					}
				}
			}
		}

		.container-bottom {
			position: fixed;
			width: 100%;
			height: 183rpx;
			background: #182836;
			box-shadow: 0px -2rpx 10rpx 0px rgba(255, 255, 255, 0.08);
			border-radius: 56rpx 56rpx 0px 0px;
			box-sizing: border-box;
			bottom: -1px;

			.btn {
				position: relative;
				width: 686rpx;
				height: 120rpx;
				// background: linear-gradient(0deg, #10A383 0%, #48C282 100%);
				background: linear-gradient(180deg, #00FFF6 0%, #28C0FF 100%);
				border-radius: 60rpx;
				display: flex;
				display: -webkit-flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;
				box-sizing: border-box;
				margin: 24rpx auto 0;
				line-height: 36rpx;
				font-size: 36rpx;
				font-family: PingFang SC;
				font-weight: 600;
				// color: #FFFFFF;
				color:#182836;

				.icon-go {
					position: absolute;
					width: 92rpx;
					height: 92rpx;
					background: #FFFFFF;
					border-radius: 50%;
					box-sizing: border-box;
					top: 50%;
					right: 14rpx;
					transform: translate(0, -50%);
					-webkit-transform: translate(0, -50%);

					.img-go {
						position: absolute;
						width: 48rpx;
						height: 48rpx;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
						-webkit-transform: translate(-50%, -50%);
					}
				}
			}

		}

		.box-share {
			position: relative;
			width: 42rpx;
			height: 42rpx;
			overflow: hidden;
		}

		.icon-share {
			position: relative;
			width: 42rpx;
			height: 42rpx;
			vertical-align: top;
		}

		.btn-share {
			position: absolute;
			width: 42rpx;
			height: 42rpx;
			width: 100%;
			height: 100%;
			overflow: hidden;
			opacity: 0;
			top: 0;
		}

	}
</style>